using System;
using System.Windows.Forms;
using System.ComponentModel;

namespace ICSharpCode.TextEditor.UserControls
{
	internal class Int32TextBox : TextBox
	{
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int Min { get; set; }
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int Max { get; set; }

		public Int32TextBox()
			: this(1, int.MaxValue)
		{
		}

		public Int32TextBox(int min, int max)
		{
			this.Min = min;
			this.Max = max;
		}

		protected override void OnTextChanged(EventArgs e)
		{
			base.OnTextChanged(e);
			if (!this.IsValidNumber(this.Text))
			{
				this.Text = string.Empty;
			}
		}

		protected override void WndProc(ref Message m)
		{
			if (m.Msg == 770)
			{
				string text = Clipboard.GetText();
				if (!this.IsValidNumber(text))
				{
					return;
				}
			}
			base.WndProc(ref m);
		}

		private bool IsValidNumber(string text)
		{
			if (int.TryParse(text, out var result))
			{
				return result <= this.Max && result >= this.Min;
			}
			return false;
		}
	}
}
